Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
由題意及範例可知,需要提供一個函式,此函式的參數為一個非負的整數,當此值為偶數時則除以 2,奇數則進行減 1,經過多少次處理後才會為 1,將次數回傳。
var count = 0;
var numberOfSteps = function(num) {
if(num === 0) return 0
else if(num === 1) return 1
else return 1 + numberOfSteps( num % 2 !== 0 ? num - 1 : Math.floor(num/2) )
};
理解完題目的需求後,腦海則是馬上浮現出了「遞迴」
,所以此題就以遞迴的方式來進行解題。